package ck.mmd.dao;

import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import ck.mmd.bean.Knowledge;
import ck.mmd.util.DaoUtils;

public class KnowledgeDao {
	/**
	 * 查询所有知识
	 * @return 返回知识的list
	 */
	public List<Knowledge> findAllKnowledgeByType(String type){
		String sql = "select * from article where type_id = ? order by uptime desc";
		try{
			QueryRunner runner = new QueryRunner(DaoUtils.getSource());
			return runner.query(sql, new BeanListHandler<Knowledge>(Knowledge.class),type);
		}catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 查找id对应的宠物知识
	 * @param id 文章id
	 * @return 返回Knowledge对象
	 */
	public Knowledge findKnowledgeById(String id) {
		String sql = "select * from article where id = ?";
		try{
			QueryRunner runner = new QueryRunner(DaoUtils.getSource());
			return runner.query(sql,new BeanHandler<Knowledge>(Knowledge.class),id);
		}catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 根据类别查找4个最新的宠物知识
	 * @param size 
	 * @param type 
	 * @return 
	 */
	public List<Knowledge> findKnowledgeBySort(int size, String type) {
		String sql = "select id,up_id,imgurl,title from article where type_id = ? order by uptime desc limit ?";
		try{
			QueryRunner runner = new QueryRunner(DaoUtils.getSource());
			return runner.query(sql, new BeanListHandler<Knowledge>(Knowledge.class),type,size);
		}catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 查找2个最新的宠物知识
	 * @param size  
	 * @return 
	 */
	public List<Knowledge> findKnowledgeBySort(int size) {
		String sql = "select id,up_id,imgurl,title,text from article order by hotnum desc limit ?";
		try{
			QueryRunner runner = new QueryRunner(DaoUtils.getSource());
			return runner.query(sql, new BeanListHandler<Knowledge>(Knowledge.class),size);
		}catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
}
